import React, { Component } from 'react';

export default function asyncComponent(importComponent) {

  let getComponent = null;

  if (typeof importComponent === 'function') {
    getComponent = importComponent;
  }

  class AsyncComponent extends Component {

    static Component = null;

    static loadComponent() {
      return Promise.resolve()
        .then(() => getComponent())
        .then(m => m.default)
        .then(Component => {
          AsyncComponent.Component = Component;
          return Component;
        });
    }

    constructor(props) {
      super(props);
      this.state = {
        component: null
      }
    }
    
    componentDidMount() {
      if (getComponent) {
        AsyncComponent.loadComponent()
        .then(Component => {
          this.setState({
            component: Component
          });
        });
      }
    }

    render() {
      const { component: C } = this.state;
      return (
        C ? <C {...this.props}/> : null
      );
    }
  }

  return AsyncComponent;
}